import { message } from 'ant-design-vue';
import { get } from 'lodash';

const messageKey = 'message_unique_key';

function tryToParseJson(str) {
  if (!str || typeof str !== 'string') {
    return str;
  }
  try {
    const obj = JSON.parse(str);
    return typeof obj === 'object' && obj ? obj : str;
  } catch (error) {
    return str;
  }
}

export function handleResponse(res, option, onOk, onFail) {
  // console.log(res);
  const opt = { errMsg: '获取数据失败', okMsg: null, silent: false };
  option = Object.assign({}, opt, option);
  if (typeof onOk !== 'function') onOk = (ok) => ok;
  if (typeof onFail !== 'function') onFail = (fail) => fail;
  if (res && res.code == 200) {
    if (option.silent !== true && option.okMsg) {
      message.success({ content: option.okMsg, key: messageKey });
    }
    return onOk(typeof option.onOk === 'function' ? option.onOk(res) : undefined);
  } else {
    if (option.silent !== true) {
      message.error({ content: (res && res.msg) || option.errMsg, key: messageKey });
    }
    return onFail(typeof option.onFail === 'function' ? option.onFail(res) : undefined);
  }
}

export function handleFormResult(res, option = {}) {
  const opt = { baseText: '操作', okText: '成功', failText: '失败' };
  option = Object.assign({}, opt, option);
  option.okMsg = option.baseText + option.okText;
  option.errMsg = option.baseText + option.failText;
  if (typeof option.silent !== 'boolean') {
    option.silent = false;
  }
  return handleResponse(
    res,
    option,
    (ok) => (typeof ok === 'boolean' ? ok : true),
    (fail) => (typeof fail === 'boolean' ? fail : false)
  );
}

export function handleTableResult(res, option = {}) {
  const opt = { totalKey: 'data.count', dataKey: 'data.list', defaultValue: [] };
  option = Object.assign({}, opt, option);
  return handleResponse(
    res,
    option,
    () => {
      const total = get(res, option.totalKey);
      const data = get(res, option.dataKey);
      return { data: tryToParseJson(data) || option.defaultValue, total: total || 0 };
    },
    () => {
      return { data: option.defaultValue, total: 0 };
    }
  );
}

export function handleCommonResult(res, option = {}) {
  const opt = { dataKey: 'data', defaultValue: [] };
  option = Object.assign({}, opt, option);
  return handleResponse(
    res,
    option,
    () => {
      return tryToParseJson(get(res, option.dataKey)) || option.defaultValue;
    },
    () => {
      return option.defaultValue;
    }
  );
}
